import React from 'react';
import {inject, observer} from 'mobx-react';
import {Modal, Tooltip} from 'antd';
import {WeaTableEditable, WeaSearchGroup,WeaLocaleProvider} from 'ecCom';
import SearchGroupBorderLeft from '../SearchGroupBorderLeft';
import PlanDetail from './PlanDetail';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
const getUserLanguage  = WeaLocaleProvider.getUserLanguage ;
@inject ('planReportViewStore')
@observer
export default class ThisMonthWorkPlan extends React.Component {
  constructor (props) {
    super (props);
    this.state = {
      detailContent: '',
    };
    this.store = this.props.planReportViewStore;
  }

  willAdd = (datas, addData) => {
    datas.pop ();
    this.store.planSummaryModal.type = 'plan';
    this.store.planSummaryModal.title = getLabel('407','计划') ;
    this.store.planSummaryModal.planSummaryModalVisible = true;
    this.store.planSummaryModal.rowIndex = -1;
    return datas;
  };

  willDelete = (datas, keys) => {
    this.store.resData.planlist = datas;
    return true;
  };
  getTableProps = () => {
    const {planmap} = this.store.resData

    let _this = this;
    let tableProps={
      onRowClick: (...arg) => {
        if (_this.canEditPlan ()) {
          _this.store.planSummaryModal.type = 'plan';
          _this.store.planSummaryModal.title = getLabel('18170','工作计划') ;
          _this.store.planSummaryModal.editData = arg[0];
          _this.store.planSummaryModal.planSummaryModalVisible = true;
          _this.store.planSummaryModal.edit = true;
        }
      },
    }
    tableProps.scroll={x:planmap.totalwidth+'%'}

    return tableProps;
  };
  canEditPlan = () => {
    return this.store.buttonAuth.edit;
  };

  //查看明细 弹出明细弹窗
  viewDetail (e, text, record, index, onEdit, dataType, callType) {
    e.stopPropagation ();
    let {category, resourceid,planlist,planstatus} = this.store.resData;

    let canedit = this.store.buttonAuth.edit;
    delete record.fbdate;
    if (record.id.indexOf ('temp') != -1) {
      record.id = '';
    }
    let _this = this;
    let detailData = '[' + JSON.stringify (record) + ']';
    this.store.saveDetailView ({
      type1:_this.store.tabSelectKey,
      operation: 'save_detail',
      resourceid: resourceid,
      plandetailid: record.id,
      dataType: dataType,
      detailData: detailData,
      doback: function (detailid) {
        planlist[index].id=detailid
        _this.setState ({
          detailContent: (
            <PlanDetail ecId={`${this && this.props && this.props.ecId || ''}_PlanDetail@0ajl2g`}
              detailid={detailid}
              category={category}
              datatype={dataType}
              canedit={canedit}
              resourceid={resourceid}
              rowIndex={index}
              visible={true}
              onClose={ _this.closeDia}
              type={'report'}
              planstatus={planstatus}
            />
          ),
        });
      },
    });
  }


   //回调关闭dialog
   closeDia = (params,detailid) => {
     params['viewdate']=''
     delete params['viewdate']
    this.setState ({detailContent: ''});
    if(params){
      let {planlist} = this.store.resData;
      let thisRow = {}
      let rowIndex=-1

      planlist.map((v,i)=>{
        if(v.id==detailid){
          thisRow=v
          rowIndex=i
        }
      })
      for(let k in params){
        thisRow[k] = params[k]
      }

      for(let k in thisRow){
        if(k && !k.startsWith("s_")){
          if(params[k]){
            thisRow[k] =  params[k]
            if(!k.startsWith("s_")){
              thisRow["s_"+k] =  typeof(thisRow[k])=='string'? thisRow[k].replace(/\n/g, "<br/>"):thisRow[k]
            }
          }else{
            thisRow[k] = ''
            if(!k.startsWith("s_")){
              thisRow["s_"+k]=''
            }
          }
        }
      }
      thisRow["id"]=detailid
      planlist[rowIndex]=thisRow
      

    }
  };

  openAdd = (rowIndex) => {
    this.store.planSummaryModal.type = 'plan';
    this.store.planSummaryModal.title = getLabel('18170','工作计划') ;
    this.store.planSummaryModal.planSummaryModalVisible = true;
    this.store.planSummaryModal.edit = false;
    this.store.planSummaryModal.rowIndex = rowIndex;
  };
  addOperationColumns = columns => {
    let {edit} = this.store.buttonAuth;
    columns.push ({
      title: <span />,
      dataIndex: 'op',
      width: '0',
      key: 'op',
      com: [
        {
          type: 'CUSTOM',
          key: 'op',
          render: (text, record, index, onEdit) => (
            <div className="operation-col">
              <div className="icon-context">
              {edit &&
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@7qu4lh@${index}`} title={getLabel('509025','新增一行数据') }>
                  <span>
                    <i
                      className="icon-coms-Left"
                      onClick={e => {
                        e.stopPropagation ();
                        this.openAdd (index);
                      }}
                    />{' '}
                  </span>
                </Tooltip>}
              {this.store.resData.createtask &&
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@mhalhz@${index}`} title={getLabel('16336','创建任务') }>
                  <span>
                    <i
                      className="icon-coms-plus"
                      onClick={e =>
                        this.createTask (e, text, record, index, onEdit, '2')}
                    />
                    {' '}
                  </span>
                </Tooltip>}
              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@lztga0@${index}`} title={getLabel('382624','查看明细')}>
                <span>
                  <i
                    className="icon-coms-form-copy"
                    onClick={e =>
                      this.viewDetail (e, text, record, index, onEdit, '2')}
                  />
                  {' '}
                </span>
              </Tooltip>
              </div>
            </div>
          ),
        },
      ],
    });
  };

  //创建任务
  createTask (e, text, record, index, onEdit, dataType, type) {
    e.stopPropagation ();
    if (record.name == undefined || record.name.length == 0) {
      Modal.warning ({
        title: getLabel('558','提示') ,
        content: getLabel('509022','请填写标题!') ,
      });
      return;
    }
    let { resourceid,planlist} = this.store.resData;

    delete record.fbdate;
    if (record.id.indexOf ('temp') != -1) {
      record.id = '';
    }
    let detailData = '[' + JSON.stringify (record) + ']';
    let _this = this;

    Modal.confirm ({
      title: getLabel('131329','信息确认'),
      content: getLabel('509023','确定创建任务？') ,
      onOk () {
        let param = {};
        param.taskName = record.name;
        param.principalid = _this.store.resData.resourceid;
        param.begindate = record.begindate1?record.begindate1:record.begindate2;
        param.enddate = record.enddate1?record.enddate1:record.enddate2;

        if(record.id==''){

          _this.store.saveDetailView ({
            type1:_this.store.tabSelectKey,
            operation: 'save_detail',
            resourceid: resourceid,
            plandetailid: record.id,
            dataType: dataType,
            detailData: detailData,
            doback: function (detailid) {
              planlist[index].id=detailid
              record.id=detailid
              param.plandetailid = detailid;
              _this.store.addTask (param,planlist[index]);
            },
          });
        }else{
          param.plandetailid = record.id;
          _this.store.addTask (param,planlist[index]);
        }


      },
      onCancel () {},
    });
  }
  render () {
    let {planReportViewStore} = this.props;
    let {dateSelect, tabSelectKey, planColumns, resData} = planReportViewStore;
    resData = toJS (resData);
    dateSelect = toJS (dateSelect);
    planColumns = toJS (planColumns);
    if(dateSelect.month.length<2){
      dateSelect.month = "0"+dateSelect.month
    }
    this.addOperationColumns (planColumns);
    let {planlist} = resData;
    let showMonth = dateSelect.month == 12
      ? 1
      : parseInt (dateSelect.month) + 1;
    let showYear = dateSelect.month == 12
      ? parseInt (dateSelect.year) + 1
      : dateSelect.year;
    if((""+showMonth).length<2){
      showMonth = "0"+showMonth
    }
    let borderMonthTitle = getUserLanguage()==8? 
    `${showYear}-${showMonth} work plan`
    :
    `${showYear}${getLabel('26577','年')}${showMonth}${getLabel('18136','月工作计划')} `
    //showYear + getLabel('26577','年') + parseInt (showMonth) + getLabel('18136','月工作计划') 
    let showWeek = (parseInt(dateSelect.week) == 53 || parseInt(dateSelect.week) == 52)?1:parseInt(dateSelect.week)+1
    tabSelectKey==2 && (showYear = (parseInt(dateSelect.week) == 53 || parseInt(dateSelect.week) == 52)?parseInt(showYear)+1:showYear)
    let borderWeekTitle = getUserLanguage()==8? 
    `${showYear} Week ${showWeek} work plan`
    :
    `${showYear}${getLabel('26577','年')}${showWeek}${getLabel('30842','周工作计划')} `
  
    return (
      <div className="this-month">
        <SearchGroupBorderLeft ecId={`${this && this.props && this.props.ecId || ''}_SearchGroupBorderLeft@wyd4cq`}
          title={
            <div>
              <i className="icon-coms-content-o" style={{color: 'blue'}} />
              {' '}
              {tabSelectKey == '1'
                ? borderMonthTitle
                : borderWeekTitle}
            </div>
          }
          color="#4F97FF"
        >

            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@vxcvr9`}
              // showTitle={true}
              draggable={false}
              pushTitleIntoHeader={false}
              columns={planColumns}
              buttonsType="inline"
              datas={planlist}
              willAdd={this.willAdd}
              willDelete={this.willDelete}
              showCopy={false}
              tableProps={this.getTableProps ()}
              showAdd={this.canEditPlan ()}
              showDelete={this.canEditPlan ()}
              getRowSelection={rowSelection => {
                return !this.canEditPlan () ? false : rowSelection;
              }}
             
            />
          {/* </WeaSearchGroup> */}
        </SearchGroupBorderLeft>
        {this.state.detailContent}

      </div>
    );
  }
}
